package com.zhijian.warehouse.manage.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.ExcelXorHtmlUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.excel.imports.ExcelImportService;
import com.zhijian.BusinessException;
import com.zhijian.response.enums.ResponseCodeEnum;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

@Slf4j
public class ExcelUtils {
    public static void exportExcel(List<?> list, String title, String sheetName, ExcelType type, Class<?> pojoClass, String fileName,
                                   boolean isCreateHeader, HttpServletResponse response) {
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        exportParams.setType(type);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }
    
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
                                   HttpServletResponse response, ExcelType excelType) {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, excelType));
    }
    
    public static void exportExcelXssf(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF));
    }
    
    public static void exportExcelHssf(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.HSSF));
    }
    
    public static void exportExcel(List<?> list, String title, String sheetName, List<ExcelExportEntity> entityList,
                                   String fileName, HttpServletResponse response) {
        defaultExport(list, entityList, fileName, response, new ExportParams(title, sheetName));
    }
    
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        defaultExport(list, fileName, response);
    }
    
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response,
                                      ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        if (workbook != null)
            downLoadExcel(fileName, response, workbook);
    }
    
    private static void defaultExport(List<?> list, List<ExcelExportEntity> entityList, String fileName,
                                      HttpServletResponse response, ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, entityList, list);
        downLoadExcel(fileName, response, workbook);
    }
    
    public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            //throw new NormalException(e.getMessage());
            log.error("异常信息:", e);
        }
    }
    
    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null)
            ;
        downLoadExcel(fileName, response, workbook);
    }
    
    
    public static <T> List<T> importExcel(String filePath,ImportParams params, Class<T> pojoClass) {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
            //throw new NormalException("模板不能为空");
            log.error("异常信息:", e);
        } catch (Exception e) {
            log.error("异常信息:", e);
            //throw new NormalException(e.getMessage());
        }
        return list;
    }
    
    
    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
            //throw new NormalException("模板不能为空");
            log.error("异常信息:", e);
        } catch (Exception e) {
            log.error("异常信息:", e);
            //throw new NormalException(e.getMessage());
        }
        return list;
    }
    
    public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass, ImportParams params) {
        if (file == null) {
            return null;
        }
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (NoSuchElementException e) {
            // throw new NormalException("excel文件不能为空");
            log.error("异常信息:", e);
        } catch (Exception e) {
            //throw new NormalException(e.getMessage());
            log.error("异常信息:", e);
        }
        return list;
    }
    
    
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows,
                                          Class<T> pojoClass) {
        if (file == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (NoSuchElementException e) {
            // throw new NormalException("excel文件不能为空");
            log.error("异常信息:", e);
        } catch (Exception e) {
            //throw new NormalException(e.getMessage());
            log.error("异常信息:", e);
        }
        return list;
    }
    
    public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows,
                                          Class<T> pojoClass) {
        if (inputStream == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new BusinessException(ResponseCodeEnum.ERROR_DATA.code, "excel文件不能为空");
        } catch (Exception e) {
            throw new BusinessException(ResponseCodeEnum.ERROR_DATA.code, e.getMessage());
        }
        return list;
    }
    
    public static <T> ExcelImportResult<T> importExcelMore(InputStream inputstream, Class<?> pojoClass, ImportParams params) throws Exception {
        return (new ExcelImportService()).importExcelByIs(inputstream, pojoClass, params, false);
    }
    
    public static Sheet getSheet(MultipartFile file) {
        // 判断是否是excel2007格式
        boolean isE2007 = false;
        if (file.getOriginalFilename().endsWith("xlsx")) {
            isE2007 = true;
        }
        InputStream is = null;
        Workbook wb = null;
        try {
            is = file.getInputStream();
            //execelIS为InputStream流
            byte[] buf = org.apache.commons.io.IOUtils.toByteArray(is);
            //在需要用到InputStream的地方再封装成InputStream
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buf);
            // 根据文件格式(2003或者2007)来初始化
            if (isE2007) {
                wb = new XSSFWorkbook(byteArrayInputStream);
            }
            else {
                wb = new HSSFWorkbook(byteArrayInputStream);
            }
        } catch (IOException e) {
            log.error("异常信息:", e);
            throw new BusinessException(ResponseCodeEnum.ERROR_DATA);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                log.error("异常信息:", e);
            }
        }
        // 获得第一个表单
        if (wb != null) {
            // 总行数
            return wb.getSheetAt(0);
        }
        return null;
    }
    
    /**
     * 根据ftl模版导出excel数据
     *
     * @param data
     * @warn ftl位置：/resources/template
     * @see {@link ExcelXorHtmlUtil#htmlToExcel}
     */
    public static <T> void exportExcelWithFtl(String title, Map<String, Object> data, String ftlTemplate, HttpServletResponse response) {
        try {
            long startTime = System.currentTimeMillis();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(title + ".xlsx", "UTF-8"));
            //转换excel
            String html = FreemarkerUtil.generateAsString(data, "/template/", ftlTemplate);
            log.info("export data & parse data, times {}", (System.currentTimeMillis() - startTime));
            //输出excel
            @Cleanup Workbook wb = ExcelXorHtmlUtil.htmlToExcel(html, ExcelType.XSSF);
            @Cleanup OutputStream ous = response.getOutputStream();
            wb.write(ous);
            ous.flush();
            log.info("export data end, times {}", (System.currentTimeMillis() - startTime));
        } catch (Exception ex) {
            log.error("export error", ex);
            AssertCommonUtil.notNull(null, "导出失败");
        }
    }
}
